/*    file: RtpPackager.cpp
 *    desc:
 * 
 * created: 2014-07-21 15:24:43
 *  author: zhengchuanjiang
 * company: 
 */

#include "stdafx.h"
#include "RtpPackager.h"
#include "RtpHeader.h"


RtpPackager::RtpPackager():
    m_file()
{

}

RtpPackager::~RtpPackager()
{
    close();
}

bool RtpPackager::open(const char* filename)
{
    fopen_s(&m_file, filename, "wb");
    return (m_file != NULL);
}

bool RtpPackager::isOpen()
{
    return (m_file != NULL);
}

void RtpPackager::close()
{
    if (m_file)
    {
        fclose(m_file);
        m_file = NULL;
    }
}


static unsigned char s_startCode[] = { 0, 0, 0, 1};

void RtpPackager::write(BYTE* ptr, UINT16 size)
{
    if (!isOpen())
    {
        return;
    }

	RTP_FIXED_HEADER* rtpHeader = (RTP_FIXED_HEADER*)ptr;
	if (size <= sizeof(RTP_FIXED_HEADER))
	{
		return;
	}

	int extSize = 0;
	if (rtpHeader->extension)
	{
		int16_t len = *((int16_t*)(ptr + sizeof(RTP_FIXED_HEADER)+2));
		len = ntohs(len);
		extSize = len * 4 + 4;
	}
    
    BYTE* pPayload = ptr + sizeof(RTP_FIXED_HEADER) + extSize;
    size_t  length = size - sizeof(RTP_FIXED_HEADER) - extSize;
    
    fwrite(pPayload, 1, length, m_file);
	fflush(m_file);
    
}
